<template>
  <div class="add-purchase-wrap">
    <PurchaseEditModule type="add" ref="purchaseEditModule" :addModel="addModel" />
    <div class="flex-c-c handle-btn-w">
      <a-space>
        <a-button class="gray-outline" size="medium" @click="showModel = true">取消</a-button>
        <a-button class="gray-outline" :disabled="submitLoading" size="medium" @click="createPlan(1)">保存草稿</a-button>
        <a-button type="primary" :disabled="submitLoading" size="medium" @click="createPlan(10)">保存并提交审核</a-button>
      </a-space>
    </div>
    <a-modal v-model:visible="showModel" title-align="start" ok-text="退出" @ok="closePage">
      <template #title>
        <p class="flex-c">
          <icon-exclamation-circle class="warn-icon" />
          <span>确认退出当前界面</span>
        </p>
      </template>
      <p>确认退出【采购计划】界面</p>
      <p>注意：当前内容未保存，关闭后数据无法恢复！</p>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onBeforeUnmount } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import useVisitedRouteStore from '@/store/modules/visited-routes'
  import { useRouter, useRoute } from 'vue-router'
  import PurchaseEditModule from './components/purchaseEditModule.vue'
  import { createPurchasePlan } from '@/api/purchase'

  const visitedRouteStore = useVisitedRouteStore()
  const route = useRoute()
  const router = useRouter()
  const showModel = ref(false)
  const purchaseEditModule = ref()
  const addModel = ref(route.query.addModel || 'purchasePlan')
  const submitLoading = ref(false)

  // 关闭界面
  function closePage() {
    if (addModel.value === 'replenishment') {
      router.push('/purchase/purchaseManagement/replenishment')
    } else {
      router.push('/purchase/purchaseManagement/purchasePlan')
    }
    visitedRouteStore.removeVisitedRoute(route)
  }
  // 创建申购计划
  async function createPlan(status: number) {
    let valid = await purchaseEditModule.value.validateData()
    if (!valid) return
    let saveData = purchaseEditModule.value.getSavaData()
    saveData.status = status
    submitLoading.value = true
    const res: any = await createPurchasePlan(saveData)
    submitLoading.value = false
    if (res) {
      Message.success('保存成功！')
      closePage()
    }
  }
  onBeforeUnmount(() => {
    // window.localStorage.removeItem('addPurchasePalnIds')
  })
</script>
<style lang="less" scoped>
  .add-purchase-wrap {
    height: calc(100vh - @menuHeight);
    display: flex;
    flex-direction: column;
  }
  .handle-btn-w {
    padding: 10px 0;
    background-color: #fff;
    .arco-btn {
      min-width: 80px;
    }
  }
  .warn-icon {
    color: rgb(var(--warning-6));
    font-size: 20px;
    margin-right: 5px;
  }
</style>
